import { mapState } from 'vuex';

const CYCLE_TIME = 30000;

const timer = {
    data() {
        return {
            serveTime: this.$store.state.currentTime || 0,
            setTimeInter: null,
            timeout: null,
            time: {
                h: '00',
                m: '00',
                s: '00',
            },
            singleTime: {
                h0: '',
                h1: '',
                m0: '',
                m1: '',
                s0: '',
                s1: '',
            },
        };
    },
    computed: {
        ...mapState(['currentTime']),
    },
    methods: {
        //根据时间戳计算剩余的时分秒
        computeHMS(intervalTime) {
            let h = '',
                m = '',
                s = '';
            h = Math.floor(intervalTime / 1000 / 60 / 60)
                .toString()
                .padStart(2, '0');
            m = Math.floor((intervalTime / 1000 / 60) % 60)
                .toString()
                .padStart(2, '0');
            s = Math.floor((intervalTime / 1000) % 60)
                .toString()
                .padStart(2, '0');
            this.time = { h, m, s };
            this.singleTime = {
                h0: h.slice(0, 1),
                h1: h.slice(1),
                m0: m.slice(0, 1),
                m1: m.slice(1),
                s0: s.slice(0, 1),
                s1: s.slice(1),
            };
        },
        // 传入时间大于服务器时间时，每隔30秒更新一次服务器时间，获取一次详情数据
        getServeTime(time) {
            if (this.setTimeInter) {
                clearTimeout(this.setTimeInter);
            }
            this.serveTime = this.currentTime;
            this.getDrillDetail(); // 调用后重新获取一次数据
            this.setTime(time);
            if (time + CYCLE_TIME > this.serveTime) {
                //多请求一个周期
                this.timeout = setTimeout(() => {
                    this.getServeTime(time);
                }, CYCLE_TIME);
            } else {
                clearTimeout(this.timeout);
            }
        },
        //设置时间
        setTime(endTime) {
            if (endTime >= this.serveTime) {
                let inter = endTime - this.serveTime;
                this.computeHMS(inter);
                this.serveTime += 1000;
            }
            clearTimeout(this.setTimeInter);
            this.setTimeInter = setTimeout(() => {
                this.setTime(endTime);
            }, 1000);
        },
        // 获取服务器后会立即执行的方法，需要各引入本mixin的组件自行覆盖
        getDrillDetail() {
            throw new Error('请覆盖getDrillDetail方法，本方法会在获取服务器时候后立即执行');
        },
    },
    watch: {
        time(newVal) {
            if (newVal.h === '00' && newVal.m === '00' && newVal.s === '00') {
                setTimeout(() => {
                    // 倒计时结束，一秒后获取新的数据
                    this.getDrillDetail();
                }, 1000);
            }
        },
    },
    beforeDestroy() {
        clearTimeout(this.timeout);
        clearTimeout(this.setTimeInter);
    },
};

export default timer;
